/*
 * @Description:
 * @Date: 2024-05-14 08:44:08
 * @LastEditTime: 2024-08-27 16:04:41
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'

const initState = {
  nickname: '',
  avatar: '',
  token: '',
  tenantId: '',
  phone: '',
  openid: '',
  userId: '',
  zhuanId: '',
  jianChaId: '',
  currentRole: '',
}

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo>({ ...initState })

    const setUserInfo = (val: IUserInfo) => {
      const {
        token,
        tenantId,
        phone,
        openid,
        userId,
        nickname,
        zhuanId,
        jianChaId,
        zhuanRenId,
        currentRole,
      } = val
      token ? (userInfo.value.token = token) : null
      tenantId ? (userInfo.value.tenantId = tenantId) : null
      phone ? (userInfo.value.phone = phone) : null
      openid ? (userInfo.value.openid = openid) : null
      userId ? (userInfo.value.userId = userId) : null
      nickname ? (userInfo.value.nickname = nickname) : null
      zhuanId ? (userInfo.value.zhuanId = zhuanId) : null
      jianChaId ? (userInfo.value.jianChaId = jianChaId) : null
      currentRole ? (userInfo.value.currentRole = currentRole) : null
      zhuanRenId ? (userInfo.value.zhuanRenId = zhuanRenId) : null
    }
    const clearUserInfo = () => {
      userInfo.value = { ...initState }
    }
    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...initState }
    }
    const isLogined = computed(() => !!userInfo.value.token)

    return {
      userInfo,
      setUserInfo,
      clearUserInfo,
      isLogined,
      reset,
    }
  },
  {
    persist: true,
  },
)
